﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;

namespace LegSec.NugetThirdPartyLicenseFileGenerator
{
    public class XmlLicenseWriter : ILicenseInformationWriter
    {
        private string File;
        public const string PACKAGE_NAME_VALUE = "title";
        public const string PACKAGE_AUTHORS_VALUE = "authors";
        public const string PACKAGE_VERSION_VALUE = "version";
        public const string PACKAGE_LICENSE_URI_VALUE = "licenseUrl";
        public const string ROOT_ELEMENT_TAG = "NugetPackages";
        public const string PACKAGE_ELEMENT_TAG = "NugetPackage";

        public string IgnoredNameSpace { get; private set; }

        public XmlLicenseWriter(string file, string ignoredNameSpace)
        {
            File = file;
            IgnoredNameSpace = ignoredNameSpace;
        }
        

        public void WriteLicences(List<PackageLicenseInformation> licenceInformationList)
        {
            XmlTextWriter xmlTextWriter = new XmlTextWriter(File, Encoding.Default);
            xmlTextWriter.Formatting = Formatting.Indented;
            xmlTextWriter.WriteStartDocument();
            xmlTextWriter.WriteComment("Generated by LegSec 3rd party licence file generator");
            xmlTextWriter.WriteStartElement(ROOT_ELEMENT_TAG);
            
            foreach (var licenseInformation in licenceInformationList)
            {
                if (IgnoredNameSpace.Equals(String.Empty) || !licenseInformation.PackageName.StartsWith(IgnoredNameSpace))
                {
                    WriteLicenceInformation(licenseInformation, xmlTextWriter);
                }
            }
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndDocument();

            xmlTextWriter.Close();
        }

        private void WriteLicenceInformation(PackageLicenseInformation licenseInformation, XmlTextWriter xmlTextWriter)
        {
            xmlTextWriter.WriteStartElement(PACKAGE_ELEMENT_TAG);
            xmlTextWriter.WriteStartElement(PACKAGE_NAME_VALUE);
            xmlTextWriter.WriteString(licenseInformation.PackageName);
            xmlTextWriter.WriteEndElement();

            xmlTextWriter.WriteStartElement(PACKAGE_VERSION_VALUE);
            xmlTextWriter.WriteString(licenseInformation.PackageVersion);
            xmlTextWriter.WriteEndElement();

            xmlTextWriter.WriteStartElement(PACKAGE_AUTHORS_VALUE);
            xmlTextWriter.WriteString(licenseInformation.AuthorName);
            xmlTextWriter.WriteEndElement();

            xmlTextWriter.WriteStartElement(PACKAGE_LICENSE_URI_VALUE);
            xmlTextWriter.WriteString(licenseInformation.LicenceUri);
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndElement();
        }
    }
}
